<?php

/**
 * 商品模型
 */
class GoodsModel extends BaseModel {

    public $ids_array = array();

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{goods}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        return array(
            array('goodsbm_id', 'required', 'message' => '报名表ID不能为空！', 'on' => 'goodsBmAdd'),
            array('cat_id', 'required', 'message' => '商品分类不能为空！'),
            array('product_id', 'required', 'message' => '商品ID不能为空！'),
            array('goods_name', 'required', 'message' => '商品标题不能为空！'),
            array('detail_url', 'required', 'message' => '商品地址不能为空！'),
            array('product_img', 'required', 'message' => '商品图片不能为空！'),
            array('listorder', 'default', 'value' => 0),
            array('p_price', 'required', 'message' => '商品原价不能为空！'),
            array('start_time', 'required', 'message' => '商品活动开始日期不能为空！'),
            array('end_time', 'required', 'message' => '商品活动结束日期不能为空！'),
            //无需验证字段
            array('goodsbm_id,tags,brand_id,goods_brief,item_type,is_best,is_new,is_hot,level,click_url,shop_click_url,seller_credit_score,home_img,module_img,add_time,status,moduleid,commission_rate,promo_price,nick,nick_add,state,city,is_stock,stock,freeshipping,is_vip,sales,start_sales,update_sales_time,uid,desc,isyugao,status_savetime,is_format,view,special_id', 'safe'),
        );
    }

    //数据保存前操作
    protected function beforeSave() {
        if ($this->cat_id) {
            //模块Id
            $this->moduleid = CategoryModel::model()->getModuleId($this->cat_id);
        }
        //时间处理
        if (!is_numeric($this->start_time)) {
            $this->start_time = strtotime($this->start_time);
        }
        if (!is_numeric($this->end_time)) {
            $this->end_time = strtotime($this->end_time);
        }
        //是否新增
        if ($this->isNewRecord) {
            //添加时间
            $this->add_time = time();
        } else {
            
        }
        return true;
    }

    //数据保存后回调
    protected function afterSave() {
        parent::afterSave();
        //更新缓存
        $this->updateCache();
        //是否新增
        if ($this->isNewRecord) {
            
        }
    }

    //数据删除后回调
    protected function afterDelete() {
        parent::afterDelete();
        //更新缓存
        $this->updateCache();
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Goods the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * 添加商品
     * @param type $data 数据
     * @return boolean
     */
    public function add($data = array()) {
        if (empty($data)) {
            $data = $_POST;
        }
        //检测同一个宝贝是否添加过
        $info = $this->find($this->where(array('product_id' => $data['product_id'])));
        if (!empty($info) && $info->end_time < time()) {
            $this->addError('product_id', "宝贝：{$data['product_id']} 已经存在，下架时间：" . date('Y-m-d H:i:s', $info->end_time) . "，不能重复添加！");
            return false;
        }
        $this->attributes = $data;
        //新增
        $this->setIsNewRecord(true);
        //生成淘客链接
        $this->taoBaoKe($this);
        //验证并添加
        if ($this->validate() && $this->save()) {
            //标签处理
            if (!empty($this->tags)) {
                $tags = strpos($this->tags, ',') !== false ? explode(',', $this->tags) : explode(' ', $this->tags);
                TagsModel::model()->addTag($tags, $this->goods_id, $this->cat_id, $this->attributes);
            }
            //添加手动上传日志
            GoodsActionModel::model()->goodsAddActionLog($this);
            return true;
        }
        return false;
    }

    /**
     * 报名审核通过进行商品添加，表需要增加一个和报名表关联的字段
     * @param type $data
     * @return boolean
     */
    public function goodsBmAdd($data) {
        if (empty($data)) {
            return false;
        }
        $data['goodsbm_id'] = $data['goods_id'];
        $model = $this->find($this->where(array('goodsbm_id' => $data['goodsbm_id'])));
        //如果已经存在，就修改
        if (!empty($model)) {
            //已经存在的不同步状态
            unset($data['status']);
            $model->attributes = $data;
            if ($model->validate() && $model->save()) {
                return true;
            }
            return false;
        }
        //设置场景
        $this->scenario = 'goodsBmAdd';
        $this->attributes = $data;
        //进行判断商品需要预告显示
        $isInfo = $this->find($this->where(array('product_id' => $this->product_id, 'end_time' => $this->start_time)));
        if (!empty($isInfo)) {
            $this->isyugao = 1;
        }
        $this->setIsNewRecord(true);
        //验证并添加
        if ($this->validate() && $this->save()) {
            //标签处理
            if (!empty($this->tags)) {
                $tags = strpos($this->tags, ',') !== false ? explode(',', $this->tags) : explode(' ', $this->tags);
                TagsModel::model()->addTag($tags, $this->goods_id, $this->cat_id, $this->attributes);
            }
            return true;
        }
        return false;
    }

    /**
     * 编辑信息
     * @param type $data
     * @return boolean
     */
    public function editor($data) {
        if (empty($data)) {
            $this->addError('', '没有修改数据！');
            return false;
        }
        $model = $this->findByPk($data['goods_id']);
        if (empty($model)) {
            $this->addError('', '该信息不存在！');
            return false;
        }
        $modelOld = $model->attributes;
        $statusOld = $model->status;
        $model->attributes = $data;
        //生成淘客链接
        $this->taoBaoKe($model);
        //记录状态变更时间
        if ($model->status != $statusOld) {
            if ($model->status == 0) {
                $model->status_savetime = time();
            } else {
                $model->status_savetime = 0;
            }
        }
        if ($model->validate() && $model->save()) {
            //同时修改报名表中的信息
            if ($model->goodsbm_id) {
                $bm = GoodsBmModel::model()->findByPk($model->goodsbm_id);
                if (!empty($bm)) {
                    $old = $bm->status;
                    $bm->attributes = $model->attributes;
                    $bm->status = $old;
                    $bm->save();
                }
            }
            //标签处理
            if (!empty($model->tags)) {
                $tags = strpos($model->tags, ',') !== false ? explode(',', $model->tags) : explode(' ', $model->tags);
                TagsModel::model()->updata($tags, $model->goods_id, $model->cat_id, $model->attributes);
            }
            //上架时间更改后通知用户
            if ($model['uid'] && $modelOld['status'] && ($modelOld['start_time'] != $model['start_time'] || $modelOld['end_time'] != $model['end_time'])) {
                $userInfo = MembersModel::model()->getUserInfo((int) $model['uid']);
                if (!empty($userInfo)) {
                    $content = "亲，您的商品({$model['product_id']})已更改了上下架时间。更改后上架时间为" . date('Y-m-d H:i:s', $model['start_time']) . " 至 " . date('Y-m-d H:i:s', $model['end_time']) . "  详情请到“报名查询”页面查询。";
                    if (defined('YII_DEBUG') && YII_DEBUG == false) {
                        Sns::getInstance()->send($userInfo['phone'], $content);
                    }
                    $extendParams = array(
                        'title' => '商品上架时间调整通知',
                        'content' => $content,
                    );
                    MessageModel::model()->systemNotice($model['uid'], $extendParams);
                }
            }
            return true;
        }
        $this->addErrors($model->getErrors());
        return false;
    }

    /**
     * 根据商品ID删除
     * @param type $goods_id 商品ID/或者对象
     * @return boolean
     */
    public function goodsDel($goods_id) {
        if (!is_object($goods_id)) {
            //查询报名信息
            $data = GoodsModel::model()->findByPk($goods_id);
        } else {
            $data = $goods_id;
        }
        if (empty($data)) {
            return false;
        }
        //将删除商品插入到商品回收站，以便删除失败找回商品
        $goodsDelete = GoodsDeleteModel::model();
        $goodsDelete->attributes = $data->attributes;
        $goodsDelete->setIsNewRecord(true);
        //删除
        if ($goodsDelete->validate() && $goodsDelete->save()) {
            if ($data->delete()) {
                //删除标签
                TagsModel::model()->deleteAll($goods_id);
                return true;
            } else {
                //删除刚刚插入回收站的信息
                $goodsDelete->deleteByPk($goodsDelete->primaryKey);
                $this->addError('', '商品删除失败！');
                return false;
            }
        } else {
            $this->addErrors($goodsDelete->getErrors());
        }
        return false;
    }

    /**
     * 取消活动（利用用户取消报名实现）
     * @param type $object 商品ID或者商品对象
     * @return boolean
     */
    public function activity($object) {
        if (!is_object($object)) {
            $object = $this->findByPk($object);
        }
        if (empty($object)) {
            $this->addError('', '该商品不存在，无需取消活动！');
            return false;
        }
        $goodsbm_id = $object->goodsbm_id;
        if (empty($goodsbm_id)) {
            $this->addError('', '手动添加商品无法取消活动！');
            return false;
        }
        $goodsBm = GoodsBmModel::model()->findByPk($goodsbm_id);
        if (empty($goodsBm)) {
            $this->addError('', '该商品的报名信息不存在，无法取消活动！');
            return false;
        }
        //取消报名
        if (GoodsBmModel::model()->cancelBm($goodsBm)) {
            $object->delete();
            return true;
        }
        $this->addError('', '取消活动失败！');
        return false;
    }

    /**
     * 生成淘客链接
     * @param type $Object
     * @return boolean
     */
    protected function taoBaoKe($Object) {
        if (!is_object($Object)) {
            return false;
        }
        if (empty($Object->product_id)) {
            return false;
        }
        $data = TaobaoApi::getInstance()
                ->productId($Object->product_id)
                ->method('taobao.taobaoke.items.detail.get')
                ->fields('click_url,shop_click_url,seller_credit_score')
                ->getData();
        if (isset($data['taobaoke_item_details']['taobaoke_item_detail'])) {
            $Object->click_url = $data['taobaoke_item_details']['taobaoke_item_detail']['click_url'];
            $Object->shop_click_url = $data['taobaoke_item_details']['taobaoke_item_detail']['shop_click_url'];
            $Object->seller_credit_score = $data['taobaoke_item_details']['taobaoke_item_detail']['seller_credit_score'];
        }
        return true;
    }

    /**
     * 集中更新几处缓存
     * @param type $good_id
     */
    public function updateCache($good_id = 0) {
        $this->getGoodBYGoodId($good_id, false);
    }

    /**
     * 获取商品数据集合
     * @param CDbCriteria $where 可以是查询表达式（数组），也可以是 CDbCriteria 对象，也可以是 SQL的WHERE部分字符串
     * @param type $num 显示数量
     * @param type $page 传入数值类型表示启用分页，分页对象在 返回的数组下标1
     * @param type $order 排序方式
     * @param type $orderRandom 是否进行特定随机排序，默认是
     * @param type $cacheKey 是否进行缓存，如果需要，传入缓存KEY
     * @return array
     */
    public function getGoodsList($where = false, $num = 99, $page = false, $order = 'default', $orderRandom = true, $cacheKey = '') {
        if (!empty($cacheKey)) {
            $return = Yii::app()->cache->get($cacheKey);
            if (!empty($return)) {
                return $return;
            }
        }
        if (is_object($where) && $where instanceof CDbCriteria) {
            $criteria = $where;
        } else if (is_array($where)) {
            $criteria = $this->where($where);
        } else if (is_string($where)) {
            $criteria = new CDbCriteria();
            $criteria->addCondition($where);
        } else {
            $criteria = new CDbCriteria();
        }
        //排序
        switch ($order) {
            //以添加时间降序
            case 'add_time':
                $criteria->order = 'add_time DESC,listorder DESC';
                $orderRandom = false;
                break;
            //以活动价格冲倒序
            case 'promo_price':
                $criteria->order = "promo_price ASC";
                $orderRandom = false;
                break;
            //以销量降序
            case 'sales':
                $criteria->order = "sales DESC";
                $orderRandom = false;
                break;
            //以推荐降序
            case 'is_best':
                $criteria->order = "is_best DESC,listorder DESC";
                $orderRandom = false;
                break;
            case 'exchange_goods':
                $criteria->order = "listorder desc,integral asc";
                $orderRandom = false;
                break;
            case 'default':
                $criteria->order = 'start_time DESC ,listorder DESC';
                //$orderRandom = true;
                break;
            //默认以上架时间降序
            default:
                $criteria->order = $order;
        }
        //是否分页
        if ($page !== false && $num > 0) {
            $count = $this->count($criteria);
            $pager = new CPagination($count);
            $pager->pageSize = $num;
            if ($order) {
                $pager->params = array('sort' => $order);
            }
            //设置当前分页号
            $pager->setCurrentPage($page - 1 < 0 ? 0 : $page - 1);
            $pager->applyLimit($criteria);
        } else if ($num > 0) {
            //数量
            $criteria->limit = $num;
        }
        //缓存获取
        $dataList = $this->findAll($criteria);
        $cats = CategoryModel::model()->getList();
        $return = array();
        foreach ($dataList as $rs) {
            $return[$rs->goods_id] = self::convertGood($rs, $cats);
        }
        //打乱排序
        if ($orderRandom) {
            $return = $this->orderRandomForStartTime($return);
            //$this->getIds_array($return);
        }
        if ($page !== false && $num > 0) {
            $return = array($return, $pager);
        }
        if ($cacheKey) {
            $status = Yii::app()->cache->set($cacheKey, $return, 600);
        }
        return $return;
    }

    /**
     * 根据专场ID获取数据
     * @param type $special_id 专场ID
     * @param type $num 取多少条，0不限。
     * @param type $where 附加条件 数组
     * @param type $page 分页号 1为第一页
     * @param type $order 排序方式
     * @param type $orderRandom 是否随机
     * @param type $cacheKey 是否缓存
     * @return boolean
     */
    public function getSpecialGoods($special_id, $num = 0, $where = array(), $page = false, $order = 'default', $orderRandom = true, $cacheKey = '') {
        if (empty($special_id) && !is_array($where)) {
            return false;
        }
        $where = array_merge(array(
            'item_type' => array('LT', 10),
            'special_id' => $special_id,
            'status' => 1,
                ), $where);
        return $this->getGoodsList($where, $num, $page, $order, $orderRandom, $cacheKey);
    }

    /**
     * 调用Level对于的数据
     * @param type $blcok_id Level
     * @param type $num 数量
     * @return array
     */
    public static function getCustomBlockGood($blcok_id = 0, $num = 8) {
        $return = array();
        if ($blcok_id == 0 || $num == 0) {
            return $return;
        }
        $time = $_SERVER["REQUEST_TIME"];
        $max_start_time = strtotime(date('Y-m-d', time())) + 86400 * 7;
        $criteria = new CDbCriteria();
        $criteria->addCondition("level = :level and status = 1 and start_time < :max_st_time and end_time > :end_time");
        $criteria->order = 'listorder DESC,start_time ASC,promo_price ASC';
        $criteria->limit = $num;
        $criteria->params = array(
            ':level' => $blcok_id,
            ':max_st_time' => $max_start_time,
            ':end_time' => $time,
        );
        $return = self::getGoodList($criteria);
        return $return;
    }

    /**
     * 获取首页需要显示的商品
     * @param type $num 数量
     * @param type $cache 是否缓存
     * @param type $order 排序方式
     * @return type
     */
    public function getHomeGoods($num = 99, $cache = '', $order = "default") {
        $time = time();
        $page = (int) $_GET['page'];
        $max_start_time = strtotime(date('Y-m-d', $time)) + 86400;
        $where = array(
            'item_type' => array('LT', 10),
            'level' => 1,
            'status' => 1,
            'start_time' => array('LT', $max_start_time),
            'end_time' => array('GT', $time),
        );
        $cacheKey = md5("getHomeGoods_{$num}_{$page}_{$order}");
        return $this->getGoodsList($where, $num, $page, $order, true, $cache && !is_bool($cache) ? $cache : $cacheKey);
    }

    /**
     * 商品详情页蜘蛛调用
     * @param type $goods_id 商品ID
     * @param type $num 数量
     * @param type $cache
     * @return type
     */
    public function getGoodsForZhiZu($goods_id, $num = 20, $cache = '') {
        $goods_id_s = $goods_id + 10;
        $goods_id_x = $goods_id - 10;
        $objCriteria = new CDbCriteria(array(
            'condition' => "goods_id BETWEEN {$goods_id_x} and {$goods_id_s}",
        ));
        $cacheKey = md5("getGoodsForZhiZu_{$num}_{$goods_id}");
        return $this->getGoodsList($objCriteria, $num, 1, 'default', '', $cache && !is_bool($cache) ? $cache : $cacheKey);
    }

    /**
     * 获取各栏目下的商品数据，栏目ID根据$_GET['cid']获取
     * @param type $num 数量
     * @param type $cache 是否缓存
     * @param type $order 排序
     * @return type
     */
    public function getCatGoods($num = 99, $cache = true, $order = "default") {
        $time = time();
        $cid = (int) $_GET['cid'];
        $page = (int) $_GET['page'];
        $max_start_time = strtotime(date('Y-m-d', $time)) + 86400;
        $where = array(
            'item_type' => array('LT', 10),
            //'level' => 1,
            'status' => 1,
            'start_time' => array('LT', $max_start_time),
            'end_time' => array('GT', $time),
        );
        if ($cid > 0) {
            $where['cat_id'] = $cid;
        }
        $cacheKey = md5("getCatGoods_{$num}_{$order}_{$cid}_{$page}");
        return $this->getGoodsList($where, $num, $page, $order, true, $cacheKey);
    }

    /**
     * 各栏目下的上期热卖，栏目ID根据$_GET['cid']获取
     * @param type $num 数量
     * @param type $cache 是否缓存
     * @return type
     */
    public function getCatYesterdayGoods($num = 99, $cache = true) {
        $time = time();
        $cid = (int) $_GET['cid'];
        $page = (int) $_GET['page'];
        $max_start_time = strtotime(date('Y-m-d', $time)) - 86400 * 3;
        $where = array(
            'item_type' => array('LT', 12),
            'level' => 1,
            'status' => 1,
            'end_time' => array(array('GT', $max_start_time), array('LT', $time), 'AND'),
        );
        if ($cid > 0) {
            $where['cat_id'] = $cid;
        }
        $cacheKey = md5("getCatYesterdayGoods_{$num}_{$cid}_{$page}");
        return $this->getGoodsList($where, $num, $page, 'start_time DESC ,listorder DESC, sales DESC', true, $cacheKey);
    }

    /**
     * 下期预告
     * @param type $num 数量
     * @param type $cache 是否缓存
     * @return type
     */
    public function getTomorrowGoods($num = 99, $cache = true) {
        $time = time();
        $page = (int) $_GET['page'];
        $max_end_time = $time + 86400 * 1;
        $where = array(
            'item_type' => array('LT', 10),
            'status' => 1,
            'start_time' => array(array('GT', $time), array('LT', $max_end_time), 'AND'),
        );
        $cacheKey = md5("getTomorrowGoods_{$num}_{$page}");
        return $this->getGoodsList($where, $num, $page, 'listorder DESC,end_time ASC,promo_price ASC', true, $cacheKey);
    }

    /**
     * 首页推荐 Level=首页显示
     * @param type $cache
     * @return type
     */
    public function getRecommendGoods($cache = true) {
        $time = time();
        $max_start_time = strtotime(date('Y-m-d', $time)) + 86400;
        $where = array(
            'item_type' => array('LT', 10),
            'level' => 1,
            'status' => 1,
            'is_best' => 1,
            'start_time' => array('LT', $max_start_time),
            'end_time' => array('GT', $time),
        );
        $cacheKey = md5("getRecommendGoods");
        return $this->getGoodsList($where, 0, false, 'start_time DESC ,listorder DESC, sales DESC', true, $cacheKey);
    }

    /**
     * 调用全部9.9活动价格数据
     * @param type $num 数据
     * @param type $cache 是否缓存
     * @param type $order 排序规则
     * @return type
     */
    public function getJKJGoods($num = 99, $cache = true, $order = "default") {
        $time = time();
        $page = (int) $_GET['page'];
        $max_start_time = strtotime(date('Y-m-d', $time)) + 86400;
        $where = array(
            'item_type' => array('LT', 10),
            'level' => 1,
            'status' => 1,
            'start_time' => array('LT', $max_start_time),
            'end_time' => array('GT', $time),
            'promo_price' => array('LT', 10),
        );
        $cacheKey = md5("getJKJGoods_{$num}_{$order}_{$page}");
        return $this->getGoodsList($where, $num, $page, $order, true, $cacheKey);
    }

    protected static function getGoodList($criteria) {
        $goods = self::model()->findAll($criteria);
        if ($goods) {
            $CategoryModel = new CategoryModel();
            $cats = $CategoryModel->getList();
            foreach ($goods as $key => $good) {
                $return[$key] = self::convertGood($good, $cats);
            }
            return $return;
        }
        return array();
    }

    /**
     * 对商品表里数据进行处理，用于前台模板数据调用
     * @param type $good 商品数据
     * @param type $cats 栏目数据
     * @return type
     */
    public static function convertGood($good, $cats = array()) {
        if (empty($cats)) {
            $cats = CategoryModel::model()->getList();
        }
        $time = $_SERVER["REQUEST_TIME"];
        $return['start_time'] = $good->start_time;
        $return['end_time'] = $good->end_time;
        $return['listorder'] = $good->listorder;
        $return['goods_id'] = $good->goods_id;
        $return['detail_url'] = $good->detail_url;
        $return['goods_name'] = $good->goods_name;
        $return['is_format'] = $good->is_format;
        if ($good->cat_id > 0) {
            $return['cat_name'] = $cats[$good->cat_id]['cat_name'];
        } else {
            $return['cat_name'] = "其他";
        }

        $return['item_type'] = $good->item_type;
        $return['good_shoptype'] = $good->item_type == 0 ? "淘宝" : "天猫";
        $return['good_url'] = Yii::app()->createUrl('/front/good/show', array('gid' => $good->goods_id));
        $return['cat_id'] = $good->cat_id;
        $return['cat_url'] = Yii::app()->createUrl('/front/index/index', array('cid' => $good->cat_id));
        $return['is_stock'] = $good->is_stock;
        $return['product_id'] = $good->product_id;
        $return['sales'] = $good->sales;
        $return['is_format'] = $good->is_format;
        if ($good->is_stock) {
            $return['sales_str'] = "<span>已售完</span>";
        } else {
            $return['sales_str'] = "已售<span class='font-arial'>{$good->sales}</span>件";
        }
        $return['is_stock'] = $good->is_stock;
        //已经上架距离结束时间
        if ($good->start_time <= $time) {
            $return['start'] = '1';
            $timer = $good->end_time - $time;
            if ($timer > 0) {
                $d = floor($timer / 86400);
                $h = floor(($timer - $d * 86400) / 3600);
                $i = floor(($timer - $d * 86400 - $h * 3600) / 60);
                $d_str = "";
                if ($d > 0) {
                    $d_str = "<span class='font-arial'>{$d}</span>天";
                }
                $return['timer_str'] = " 剩：{$d_str}<span class='font-arial'>$h</span>时<span class='font-arial'>$i</span>分";
            }else{
                $return['timer_str'] = '';
            }
        } else {
            $return['start'] = '0';
            $timer = $good->start_time - $time;
            $d = floor($timer / 86400);
            $h = floor(($timer - $d * 86400) / 3600);
            $i = floor(($timer - $d * 86400 - $h * 3600) / 60);
            $d_str = "";
            if ($d > 0) {
                $d_str = "<span class='font-arial'>{$d}</span>天";
            }
            $return['timer_str'] = " 距开始{$d_str}<span class='font-arial'>$h</span>时<span class='font-arial'>$i</span>分";
        }

        $return['product_img'] = $good->product_img;
//        preg_match("/[png|jpg|gif](_.*x.*.[png|jpg])$/", $return['product_img'], $matches);
//        if (empty($matches)) {
//            $return['product_img'] = trim($return['product_img']) . "_250x250.jpg";
//        } else {
//            $return['product_img'] = str_replace($matches[1], '_250x250.jpg', $return['product_img']);
//        }
        $return['goods_brief'] = $good->goods_brief;
        $return['sales'] = $good->sales;
        $return['p_price'] = $good->p_price;
        $return['promo_price'] = $good->promo_price;
        $return['discount'] = "null";
        if ($good->p_price > 0) {
            $return['discount'] = round($good->promo_price / $good->p_price, 2) * 10;
        }
        return $return;
    }

    /**
     * 商品剩余多少时间处理
     * @param type $start_time 开始时间
     * @param type $end_time 结束时间
     * @return type
     */
    public static function convertWaitTime($start_time, $end_time) {
        $time = $_SERVER["REQUEST_TIME"];
        if ($start_time <= $time) {
            $return['start'] = '1';
            $timer = $end_time - $time;
            $d = floor($timer / 86400);
            $h = floor(($timer - $d * 86400) / 3600);
            $i = floor(($timer - $d * 86400 - $h * 3600) / 60);
            $d_str = "";
            if ($d > 0) {
                $d_str = "<span class='font-arial'>{$d}</span>天";
            }
            $return['timer_lalbe'] = "剩余时间";
            $return['timer_str'] = "{$d_str}<span class='font-arial'>$h</span>时<span class='font-arial'>$i</span>分";
        } else {
            $return['start'] = '0';
            $timer = $start_time - $time;
            ;
            $d = floor($timer / 86400);
            $h = floor(($timer - $d * 86400) / 3600);
            $i = floor(($timer - $d * 86400 - $h * 3600) / 60);
            $d_str = "";
            if ($d > 0) {
                $d_str = "<span class='font-arial'>{$d}</span>天";
            }
            $return['timer_lalbe'] = "距离开始";
            $return['timer_str'] = "{$d_str}<span class='font-arial'>$h</span>时<span class='font-arial'>$i</span>分";
        }
        return $return;
    }

    /**
     * 根据商品ID取得商品表数据
     * @param type $good_id goods表主键ID
     * @param type $cache 是否缓存
     * @return boolean
     */
    public function getGoodBYGoodId($good_id = null, $cache = true) {
        if (!isset($good_id) || (int) $good_id < 1) {
            if (isset($this->good_id) && (int) $this->good_id) {
                $good_id = $this->good_id;
            } else {
                return false;
            }
        }
        $key = "GoodsModel_getGoodBYGoodId_{$good_id}";
        $return = Yii::app()->cache->get($key);
        if (!empty($return) && $cache) {
            return $return;
        }
        $model = $this->findByPk($good_id);
        if (!empty($model)) {
            Yii::app()->cache->set($key, $model, 180);
            return $model;
        }
        return false;
    }

//    protected function addFilterForeshow($criteria) {
//        $time = $_SERVER["REQUEST_TIME"];
//        $now_timestamp = strtotime(date('Y-m-d', $time)) + 36000;
//        if ($time < $now_timestamp) {
//            $criteria->addCondition("isyugao=0");
//        }
//    }

    /**
     * 排序字段排序
     * @param array $data 商品数据
     * @return array
     */
    public function orderRandomForListorder($data) {
        if (empty($data)) {
            return array();
        }
        $return = array();
        foreach ($data as $k => $rs) {
            $newsData = array();
            foreach ($rs as $info) {
                $newsData[$info['listorder']][$info['goods_id']] = $info;
            }
            foreach ($newsData as $id => $rs) {
                shuffle($newsData[$id]);
            }
            $data[$k] = $newsData;
        }
        foreach ($data as $k => $rs) {
            foreach ($rs as $info) {
                foreach ($info as $v) {
                    $return[] = $v;
                }
            }
        }
        return $return;
    }

    /**
     * 根据start_time字段，然后进行随机处理
     * @param array $data 商品数据
     * @return array
     */
    public function orderRandomForStartTime($data) {
        if (empty($data)) {
            return array();
        }
        $return = array();
        $newsData = array();
        foreach ($data as $rs) {
            $newsData[$rs['start_time']][$rs['goods_id']] = $rs;
        }
        krsort($newsData);
//        foreach ($newsData as $rs) {
//            shuffle($rs);
//            $return = array_merge($return, $rs);
//        }
//        print_r($return);exit;
        return $this->orderRandomForListorder($newsData);
    }

    /**
     * 推哈网商品信息采集
     * @return array 
     */
    public function getTHWgoods() {
        $min_start_time = strtotime(date('Y-m-d 00:00:00'));
        $max_start_time = strtotime(date('Y-m-d 23:59:59'));
        $criteria = new CDbCriteria();
        $criteria->select = "goods_id,cat_id,product_id,goods_name,nick,product_img,p_price,promo_price,freeshipping,start_time,end_time";
        $criteria->addCondition("status = 1 and start_time > :min_st_time and start_time < :max_start_time");
        $criteria->order = 'listorder DESC,start_time ASC,promo_price ASC';

        $criteria->params = array(
            ':min_st_time' => $min_start_time,
            ':max_start_time' => $max_start_time,
        );
        $getTuiHaCat = array(
            1 => 1,
            2 => 4,
            3 => 9,
            4 => 5,
            5 => 2,
            6 => 8,
            7 => 5,
            8 => 7,
            9 => 3,
        );
        $goods = $this->findAll($criteria);
        if ($goods) {
            foreach ($goods as $key => $good) {
                $return[$key]['numiid'] = $good->product_id;
                $return[$key]['tuihacid'] = $getTuiHaCat[$good->cat_id] ? $getTuiHaCat[$good->cat_id] : 99;
                $return[$key]['title'] = urlencode($good->goods_name);
                $return[$key]['nick'] = urlencode($good->nick);
                $return[$key]['picurl'] = $good->product_img;
                $return[$key]['price'] = $good->p_price;
                $return[$key]['xprice'] = $good->promo_price;
                $return[$key]['baoyou'] = $good->freeshipping;
                $return[$key]['listtime'] = date('Y-m-d H:i:s', $good->start_time);
                $return[$key]['downtime'] = date('Y-m-d H:i:s', $good->end_time);
            }
            return $return;
        }

        return $goods;
    }

}
